package com.yi.mall.scheduler.service.impl;

import com.alibaba.fastjson.JSON;
import com.yi.mall.common.filter.CacheBloomFilter;
import com.yi.mall.common.model.seckill.SeckillActivity;
import com.yi.mall.common.model.seckill.SeckillGoods;
import com.yi.mall.common.utils.ResponseEnum;
import com.yi.mall.common.utils.Result;
import com.yi.mall.scheduler.service.IBuyService;
import com.yi.mall.seckill.SeckillActivityFeign;
import com.yi.mall.seckill.SeckillGoodsFeign;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private SeckillActivityFeign seckillActivityFeign;
    @Autowired
    private SeckillGoodsFeign seckillGoodsFeign;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CacheBloomFilter<Integer> cacheBloomFilter;
    @Override
    public void loadStock() {
        // 创建布隆过滤器
        RBloomFilter<Integer> bloomFilter = cacheBloomFilter.getBloomFilter(redissonClient);

        // 获取所有活动
        Result responseVO = seckillActivityFeign.listAllByToday();
        if (responseVO.getCode() != ResponseEnum.SUCCESS.getCode()){
            throw  new RuntimeException(responseVO.getMessage());
        }
        List<SeckillActivity> activityList = JSON.parseArray(JSON.toJSONString(responseVO.getData()),
                SeckillActivity.class);
        // 遍历所有活动下的商品
        for (SeckillActivity activity : activityList) {
            Result result = seckillGoodsFeign.listByActivityId(activity.getId());
            // 将数据写入布隆过滤器
            bloomFilter.add(activity.getId());
            if (result.getCode() != ResponseEnum.SUCCESS.getCode()){
                throw  new RuntimeException(result.getMessage());
            }
            List<SeckillGoods> seckillGoodsList = JSON.parseArray(JSON.toJSONString(result.getData()),
                    SeckillGoods.class);
            // 加载库存到Redis中
            for (SeckillGoods goods : seckillGoodsList) {
                // 以seckill+活动id+商品id为key，商品库存为value
                String key = String.format("seckill-%s-%s",activity.getId(),goods.getSkuId());
                redisTemplate.opsForValue().set(key,goods.getStoreCount().toString());
                redisTemplate.expire(key, 1, TimeUnit.DAYS);
            }
        }
    }
}